package com.songlin.testv2ex.model;

import android.os.Parcel;
import android.os.Parcelable;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by 松林 on 2015/10/4.
 */
public class Node extends SuperModel implements Parcelable {

    public int id;
    public String name;
    public String title;
    public String titleAlternative;
    public String url;
    public int topics;
    public String avatar;

    public String header;
    public String footer;
    public boolean isCollected = false;

    public Node() {

    }

    private Node(Parcel in) {
        int[] ints = new int[2];
        in.readIntArray(ints);
        id = ints[0];
        topics = ints[1];
        String[] strings = new String[6];
        in.readStringArray(strings);
        name = strings[0];
        title = strings[1];
        titleAlternative = strings[2];
        if( (url = strings[3]).equals("") ) {
            url = null;
        }
        if( (header = strings[4]).equals("") ) {
            header = null;
        }
        if( (footer = strings[5]).equals("") ) {
            footer = null;
        }
        boolean[] booleans = new boolean[1];
        in.readBooleanArray(booleans);
        isCollected = booleans[0];
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel parcel,int flags) {
        parcel.writeIntArray(new int[] {
                id, topics
        });
        String[] strings = new String[6];
        strings[0] = name;
        strings[1] = title;
        if((strings[2] = titleAlternative ) == null) {
            strings[2] = "";
        }
        strings[3] = url;
        if((strings[4] = header) == null) {
            strings[4] = "";
        }
        if((strings[5] = footer) == null) {
            strings[5] = "";
        }
        parcel.writeStringArray(strings);
        parcel.writeBooleanArray(new boolean [] { isCollected });
    }

    public void parse(JSONObject jsonObject) throws JSONException {
        id = jsonObject.optInt("id");
        name = jsonObject.optString("name");
        title = jsonObject.optString("title");
        if(!jsonObject.optString("titleAlternative").equals("null")) {
            titleAlternative = jsonObject.optString("title_alternative");
        }
        url = jsonObject.optString("url");
        topics = jsonObject.optInt("topics");
        if(!jsonObject.optString("header").equals("null")) {
            header = jsonObject.optString("header");
        }
        if(jsonObject.optString("footer").equals("null")) {
            footer = jsonObject.optString("footer");
        }
    }

    public static final Creator<Node> CREATOR = new Creator<Node>() {
        @Override
        public Node createFromParcel(Parcel source) {
            return new Node(source);
        }
        @Override
        public Node[] newArray(int size) {
            return new Node[size];
        }
    };
}
